from django.contrib.auth import (
    views as auth_views,
)
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.views.generic import View

from .forms import MyLoginForm
from .utils import get_default_url_of_role


class MyLoginView(auth_views.LoginView):
    form_class = MyLoginForm
    template_name = 'auth/login.html'

    def dispatch(self, request, *args, **kwargs):
        return super(MyLoginView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated and \
           not self.request.GET.get('next'):
            return redirect(get_default_url_of_role(request.user))
        else:
            return super(MyLoginView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(MyLoginView, self).get_context_data(**kwargs)
        # print('form', context['form'].errors)
        return context

    def render_to_response(self, context, **response_kwargs):
        return super(MyLoginView, self).render_to_response(
            context, **response_kwargs
        )


class MyLogoutView(auth_views.LogoutView):
    # template_name = 'auth/logout.html'
    next_page = reverse_lazy('user:login')


class UserRedirectView(LoginRequiredMixin, View):

    def get(self, request, *args, **kwargs):
        return redirect(get_default_url_of_role(request.user))
